<template>
  <!-- 最外层的容器 -->
  <view class="my-settle-container">
    <!-- 全选区域 -->
    <label class="radio" @click="changeAllState">
      <radio color="#C00000" :checked="isFullcheck" />
      <text>全选</text>
    </label>

    <!-- 合计区域 -->
    <view class="amount-box">
      合计:
      <text class="amount">￥{{ computeAllGoodsPrice }}</text>
    </view>

    <!-- 结算按钮 -->
    <view class="btn-settle" @click="settlement">结算({{ checkedCount }})</view>
  </view>
</template>

<script>
  import { mapGetters, mapMutations, mapState } from 'vuex'
export default {
  computed: {
    ...mapGetters('m_cart', ['checkedCount', 'goods_total', 'computeAllGoodsPrice']),
    ...mapGetters('m_user', ['addstr']),
    ...mapState('m_user', ['token']),
    ...mapState('m_cart', ['cart']),
    isFullcheck() {
      return this.checkedCount === this.goods_total
    }
  },
  name: 'my-settle',
  data() {
    return {
      seconds: 3,
      timer: null
    };
  },
  methods: {
    ...mapMutations('m_cart', ['updateAllState']),
    ...mapMutations('m_user', ['updateJumpInfo']),
    changeAllState() {
      // 调用 store 里面的函数修改所有商品的状态
      this.updateAllState(!this.isFullcheck)
    },
    
    // 点击结算
    settlement() {
      // $showMsg 封装在全局 main.js 中
      if (!this.checkedCount) return uni.$showMsg('请选择要结算的商品')
      if (!this.addstr) return uni.$showMsg('请选择收货地址')
      if (!this.token) return this.delayJump()
      
      // 支付功能的实现
      this.payOrder()
    },
    
    // 订单支付
    async payOrder() {
      // 第一步 创建订单
      const orderInfo = {
        order_price: 0.01,
        consignee_addr: this.addstr,
        goods: this.cart.filter(t => t.goods_state).map(x => ({
          goods_id: x.goods_id,
          goods_number: x.goods_count,
          goods_price: x.goods_price
        }))
      }
      const data = await uni.$http.post('/api/public/v1/my/orders/create', orderInfo)
      console.log(data);
      if (data.meta.status !== 200) {
        return uni.$showMsg('订单创建失败')
      }
      // 储存订单编号
      const order_number =  data.message.order_number
      
      // 第二步 订单预支付
      const { data: res } = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', { order_number })
      if (res.meta.status !== 200) {
        return uni.$showMsg('预付订单创建失败!')
      }
      // 存储订单支付必要参数
      const payInfo = res.message.pay
      
      // 第三步 发起微信支付
      const [err, succ] = await uni.requestPayment(payInfo)
      if (err) return uni.$showMsg('支付失败')
      
      // 第四步 向后端发起请求 检查订单状态是否支付成功
      const {data: result} = await uni.$http.post('/api/public/v1/my/orders/checkOrder', order_number)
      // console.log(result)
      if (data.meta.status !== 200) {
        return uni.$showMsg('订单支付失败')
      }
      uni.showToast({
        title: result.message,
        icon: 'none'
      })
    },
    
    // 倒计三秒 自动跳转到登录页
    delayJump() {
      // 重置计时器
      this.seconds = this.$options.data().seconds
      // 设置一个 定时器 每隔一秒给用户一个提示
      this.timer = setInterval(() => {
        // 当 this.seconds <= 0 时 清空定时器
        if (this.seconds <= 0) {
          clearInterval(this.timer)
          // 跳转到登录页面
          uni.switchTab({
            url: '/pages/my/my',
            success: () => {
              // 购物车信息持久化
              this.updateJumpInfo({
                opentype: 'switchTab',
                from: '/pages/cart/cart'
              })
            }
          })
          return
        }
        uni.showToast({
          icon: 'none',
          title: '请登录后再结算! 即将跳转到登录页...' + this.seconds--
        })
      }, 1000)
    }
  }
};
</script>

<style lang="scss">
.my-settle-container {
  /* 底部固定定位 */
  position: fixed;
  bottom: 0;
  left: 0;
  /* 设置宽高和背景色 */
  width: 100%;
  height: 50px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  font-size: 14px;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-settle {
    height: 50px;
    min-width: 100px;
    background-color: #c00000;
    color: white;
    line-height: 50px;
    text-align: center;
    padding: 0 10px;
  }
}
</style>
